package com.yanjiali.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yanjiali.constant.OfficialRouteConstant;
import com.yanjiali.entity.CollectContent;
import com.yanjiali.entity.SecondLevelCollect;
import com.yanjiali.enumerate.DataSourceType;
import com.yanjiali.feign.ArticleServiceFeign;
import com.yanjiali.model.R;
import com.yanjiali.model.req.AddToCollectionRecordReq;
import com.yanjiali.model.req.GetCollectDataByOneDirIdReq;
import com.yanjiali.model.req.RemoveCollectionRecordsReq;
import com.yanjiali.model.req.UpdateArticleCollectNumReq;
import com.yanjiali.model.resp.*;
import com.yanjiali.service.CollectContentService;
import com.yanjiali.service.SecondLevelCollectService;
import com.yanjiali.vo.CollectOneDirVO;
import com.yanjiali.vo.CollectTwoDirVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yanjiali.mapper.CollectMapper;
import com.yanjiali.entity.Collect;
import com.yanjiali.service.CollectService;

import java.util.List;
import java.util.stream.Collectors;

/**
* @Package: com.yanjiali.service.impl
* @Author: yanjiali
* @Created: 2025/4/19 15:06
*/
@Service
public class CollectServiceImpl extends ServiceImpl<CollectMapper, Collect> implements CollectService{

    @Autowired
    private SecondLevelCollectService secondLevelCollectService;

    @Autowired
    private CollectContentService collectContentService;    //对应收藏内容的service接口

    @Autowired
    private ArticleServiceFeign articleServiceFeign;

    @Override
    public R<AddToCollectionRecordResp> addToCollectionRecord(AddToCollectionRecordReq addToCollectionRecordReq) {
        //判断一级目录是否合法
        if(!oneDriNameIsLegal(addToCollectionRecordReq.getOneDirName())) {
            throw new IllegalArgumentException("传入的一级收藏夹不合法");
        }

        //获取登录用户的id
        String userId = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication != null) {
            userId = authentication.getPrincipal().toString();
        }else {
            throw new RuntimeException("用户未登录");
        }

        //查询用户对应二级目录是否存在
        Long twoDriID = twoDriNameIsLegal(userId, addToCollectionRecordReq.getTwoDirName());
        if(twoDriID == null) {
            throw new IllegalArgumentException("传入的二级收藏夹不合法");
        }

        //通过id获取对应文章的信息
        R<GetByIdArticleNoNeedAuthorResp> feignRespR = articleServiceFeign.getByIdArticleNoNeedAuthor(addToCollectionRecordReq.getArticleId());
        if(feignRespR.getCode() == 200) {
            GetByIdArticleNoNeedAuthorResp data = feignRespR.getData();

            //TODO 先判断是否存在
            LambdaQueryWrapper<CollectContent> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper
                    .eq(CollectContent::getTitle, data.getTitle())
                    .eq(CollectContent::getCreateBy, userId);
            CollectContent collectContent = collectContentService.getOne(lambdaQueryWrapper);

            if(collectContent == null) {    //没有存储过
                collectContent = new CollectContent();
                collectContent.setTitle(data.getTitle());
                collectContent.setCover(data.getCover());
                collectContent.setType(DataSourceType.OFFICIAL.getType());
                collectContent.setUrl(OfficialRouteConstant.OFFICIAL_ROUTE_PREFIX + addToCollectionRecordReq.getArticleId());
                collectContent.setSecondLevelCollectId(twoDriID);
                boolean save = collectContentService.save(collectContent);
                if(save) {  //记录收藏记录，同时修改文章对应的收藏数量并回显
                    R<UpdateArticleCollectNumResp> updateArticleCollectNumRespR
                            = articleServiceFeign.updateArticleCollectNum(
                                    new UpdateArticleCollectNumReq(addToCollectionRecordReq.getArticleId(), Short.valueOf("1")));
                    if(updateArticleCollectNumRespR.getCode() == 200) {
                        Long collectNum = updateArticleCollectNumRespR.getData().getCollectNum();
                        return R.ok(new AddToCollectionRecordResp(collectNum));
                    }
                }
            }else {
                return R.fail("当前文章已经收藏过了哦");
            }
        }

        return R.fail("收藏失败");
    }

    @Override
    public R<RemoveCollectionRecordsResp> removeCollectionRecords(RemoveCollectionRecordsReq removeCollectionRecordsReq) {
        //获取登录用户的id
        String userId = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication != null) {
            userId = authentication.getPrincipal().toString();
        }else {
            throw new RuntimeException("用户未登录");
        }

        R<GetByIdArticleNoNeedAuthorResp> feignRespR = articleServiceFeign.getByIdArticleNoNeedAuthor(removeCollectionRecordsReq.getArticleId());

        if(feignRespR.getCode() == 200) {
            LambdaUpdateWrapper<CollectContent> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper
                    .eq(CollectContent::getCreateBy, userId)
                    .eq(CollectContent::getTitle, feignRespR.getData().getTitle());

            boolean remove = collectContentService.remove(lambdaUpdateWrapper);
            if(remove) {
                R<UpdateArticleCollectNumResp> updateArticleCollectNumRespR
                        = articleServiceFeign.updateArticleCollectNum(
                        new UpdateArticleCollectNumReq(removeCollectionRecordsReq.getArticleId(), Short.valueOf("-1")));
                if(updateArticleCollectNumRespR.getCode() == 200) {
                    Long collectNum = updateArticleCollectNumRespR.getData().getCollectNum();
                    return R.ok(new RemoveCollectionRecordsResp(collectNum));
                }
            }
        }

        return R.fail("取消收藏失败");
    }

    @Override
    public R<GetCollectDataByOneDirIdResp> obtainTheCorrespondingDataThroughThePrimaryDirectoryId(GetCollectDataByOneDirIdReq getCollectDataByOneDirIdReq) {
        String userId = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication != null) {
            userId = authentication.getPrincipal().toString();
        }else {
            throw new RuntimeException("用户未登录");
        }

        LambdaQueryWrapper<Collect> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .eq(Collect::getId, getCollectDataByOneDirIdReq.getOneDirId());

        Collect collect = getOne(lambdaQueryWrapper);
        if(collect == null) {
            throw new IllegalArgumentException("不合法的一级目录id");
        }

        //一级基本赋值
        CollectOneDirVO collectOneDirVO = new CollectOneDirVO();
        collectOneDirVO.setId(collect.getId());
        collectOneDirVO.setName(collect.getName());

        //获取二级数据并赋值
        LambdaQueryWrapper<SecondLevelCollect> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(SecondLevelCollect::getUserId, userId)
                .eq(SecondLevelCollect::getCollectId, collect.getId())
                .or()   //TODO 或者获取的是默认二级收藏目录
                .isNull(SecondLevelCollect::getUserId)
                .eq(SecondLevelCollect::getCollectId, collect.getId());

        List<SecondLevelCollect> list = secondLevelCollectService.list(lqw);

        //TODO 存在默认收藏目录，不能删除，所有一定不为空或者<1
//        if(list == null || list.size() < 1) {
//            //TODO 此处是否抛出异常，取决于是否提供默认二级收藏夹
//            //TODO 如果公用二级收藏夹 ———— 默认收藏夹，那就去除这个收藏夹的用户字段，如果查找不到对应二级收藏夹就是直接使用这个收藏夹去收藏内容中匹配
//            throw new RuntimeException("用户没有创建与之对应的二级收藏夹");
//        }

        //将二级目录存储到一级
        for(SecondLevelCollect s : list) {
            CollectTwoDirVO collectTwoDirVO = new CollectTwoDirVO();
            collectTwoDirVO.setId(s.getId());
            collectTwoDirVO.setTitle(s.getTitle());

            collectOneDirVO.getCollectTwoDirVOList().add(collectTwoDirVO);
        }

        return R.ok(new GetCollectDataByOneDirIdResp(collectOneDirVO));
    }

    /**
     * 判断对应一级目录是否在数据库中存在
     *  因为一级目录是写死的且所有人共享的，所以不需要用户条件
     * @param oneDirName
     * @return
     */
    private Boolean oneDriNameIsLegal(String oneDirName) {
        LambdaQueryWrapper<Collect> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Collect::getName, oneDirName);
        Collect collect = getOne(lambdaQueryWrapper);
        return collect != null;
    }

    /**
     * TODO 对应用户为空说明是默认二级收藏目录
     * 判断对应二级目录是否存在
     * @param twoDirName
     * @return 如果存在返回对应id，否则返回null
     */
    private Long twoDriNameIsLegal(String userId, String twoDirName) {
        LambdaQueryWrapper<SecondLevelCollect> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .eq(SecondLevelCollect::getTitle, twoDirName)
                .eq(SecondLevelCollect::getUserId, userId)
                .or()
                .eq(SecondLevelCollect::getTitle, twoDirName)
                .isNull(SecondLevelCollect::getUserId);

        SecondLevelCollect secondLevelCollect = secondLevelCollectService.getOne(lambdaQueryWrapper);
        return secondLevelCollect.getId();
    }
}
